<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Call\Logic;

use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\User\Contract\UserContract;

/**
 * 呼叫监控.
 *
 * Class IndexLogic
 */
class MonitorIndexLogic
{
    /**
     * @Inject
     * @var UserContract
     */
    protected $userService;

    public function post($data, $url, $header)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $output = curl_exec($ch);
        return json_decode($output, true);
    }

    /**
     * 呼叫监控列表.
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function handle(array $params): array
    {
        $a = $this->post([
            'sa_user'=>env('CALL_CENTER_USERNAME'),
            'sa_password' =>md5(env('CALL_CENTER_PASSWORD')),
            'method'=>'getExtensions'
        ], env("CALL_CENTER_BASE_URL"), [
            'Content-Type:application/x-www-form-urlencoded',
        ]);
        //返回的数据格式
        $data = [];
        //请求外部接口
        $token = send_http_request(env("CALL_CENTER_BASE_URL"), '/api/login', 'GET', [
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'verify' => false,
            'query' => [
                'username' => env("CALL_CENTER_USERNAME"),
                'password' => env("CALL_CENTER_PASSWORD"),
            ]
        ]);

        $response = send_http_request(env("CALL_CENTER_BASE_URL"), '/api/ola/agents', 'GET', [
            'headers' => [
                'X-Auth-Token' => $token,
                'Content-Type' => 'application/json',
            ],
            'verify' => false,
            // 'query' => [
            //     'extn' => $params['extn'],
            // ]
        ]);
        $data = my_array_change_key($response);
        if (!empty($data['agents'])) {
            $extns = array_column($data['agents'], 'extn');
            $inCall = Db::table('call_record')->whereIn('caller_id_name', $extns)->select([
                Db::raw('COUNT(*) as count'),
                'destination_number',
            ])
                ->where('created_time', '>=', date('Y-m-d 00:00:00'))
                ->where('call_type', 'in')->groupBy(['destination_number'])->get();
            $inCall = empty($inCall) ? [] : array_column($inCall->toArray(), null, 'destination_number');

            $outCall = Db::table('call_record')->whereIn('caller_id_name', $extns)->select([
                Db::raw('COUNT(*) as count'),
                'caller_id_number',
            ])
                ->where('created_time', '>=', date('Y-m-d 00:00:00'))
                ->where('call_type', 'out')->groupBy(['caller_id_number'])->get();
            $outCall = empty($outCall) ? [] : array_column($outCall->toArray(), null, 'caller_id_number');
//            ->where('call_duration','>',0)
            $inCallPutOn = Db::table('call_record')->whereIn('caller_id_name', $extns)->select([
                Db::raw('COUNT(*) as count'),
                'destination_number',
            ])
                ->where('created_time', '>=', date('Y-m-d 00:00:00'))
                ->where('call_duration', '>', 0)
                ->where('call_type', 'in')->groupBy(['destination_number'])->get();
            $inCallPutOn = empty($inCallPutOn) ? [] : array_column($inCallPutOn->toArray(), null, 'destination_number');

            $outCallPutOn = Db::table('call_record')->whereIn('caller_id_name', $extns)->select([
                Db::raw('COUNT(*) as count'),
                'caller_id_number',
            ])
                ->where('created_time', '>=', date('Y-m-d 00:00:00'))
                ->where('call_duration', '>', 0)
                ->where('call_type', 'out')->groupBy(['caller_id_number'])->get();
            $outCallPutOn = empty($outCallPutOn) ? [] : array_column($outCallPutOn->toArray(), null, 'caller_id_number');
            //获取分机号企业员工名称
            $userName = Db::table('user')->whereIn('user.extn', $extns)
                ->join('work_employee as employee', 'employee.log_user_id', '=', 'user.id')
                ->pluck('employee.name', 'user.extn');
            $userName || $userName = collect([]);
            $userName = $userName->toArray();
            foreach ($data['agents'] as &$value) {
                //分机号对应员工名称
                $value['employeeName'] = $userName[$value['extn']] ?? '';

                $value['stopAt'] = '00:00:00';
                if ($value['updatedAt']) {
                    $totalSeconds = time() - strtotime($value['updatedAt']);
                    //小时
                    $hour = floor($totalSeconds / 3600);
                    $hourSurplusSeconds = $totalSeconds - ($hour * 3600);
                    //分钟
                    $minutes = floor($hourSurplusSeconds / 60);
                    //秒
                    $seconds = $hourSurplusSeconds - ($minutes * 60);
                    //闲置时间
                    $value['stopAt'] = $hour . ":" . $minutes . ":" . $seconds;
                }
                //今日呼入数
                $value['inCall'] = $inCall[$value['extn']]->count ?? 0;
                //今日呼出数
                $value['outCall'] = $outCall[$value['extn']]->count ?? 0;

                //今日接通
                $value['totalCall'] = ($inCallPutOn[$value['extn']]->count ?? 0) + ($outCallPutOn[$value['extn']]->count ?? 0);
            }
            unset($value);
        }

        // $data['page']['total'] = $res['total'];
        // $data['page']['totalPage'] = $res['last_page'];
        return $data;
    }
}
